<template>
  <div class="add-product">
    <el-steps :active="1" align-center class="custom-steps">
      <el-step title="填写商品信息" icon="el-icon-edit"></el-step>
      <el-step title="填写商品属性" icon="el-icon-price-tag"></el-step>
      <el-step title="添加商品图片" icon="el-icon-picture"></el-step>
      <el-step title="选择商品关联" icon="el-icon-connection"></el-step>
    </el-steps>
    <div class="page-header">
      <h2>添加新商品</h2>
    </div>
    <el-form
      :model="productForm"
      :rules="rules"
      ref="ruleForm"
      label-width="120px"
      class="input-container">
      <el-row :gutter="20">
        <el-col :span="5">
          <el-form-item label="商品分类" prop="category" required>
            <el-cascader
              v-model="productForm.category"
              :options="categoryOptions"
              :props="{
              expandTrigger: 'click',
              checkStrictly: true,
              emitPath: false
            }"
              :loading="loading"
              placeholder="请选择商品分类"
              clearable
              class="full-width"
              @change="handleCategoryChange" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="商品名称" prop="name" required>
            <el-input
              type="textarea"
              v-model="productForm.name"
              :rows="1"
              placeholder="请输入商品名称"
              resize="none"
              class="custom-textarea">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="商品货号" prop="code">
            <el-input
              type="textarea"
              v-model="productForm.code"
              :rows="2"
              placeholder="请输入商品货号"
              resize="none"
              class="custom-textarea">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="商品简介" prop="remark">
            <el-input
              type="textarea"
              v-model="productForm.remark"
              :rows="4"
              placeholder="请输入商品简介"
              resize="none"
              class="custom-textarea">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="商品SKU库存" prop="inventory">
            <el-input-number
              v-model="productForm.inventory"
              :min="0"
              controls-position="right"
              placeholder="请输入商品库存"
              class="full-width">
            </el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品销量" prop="sale">
            <el-input-number
              v-model="productForm.sale"
              :min="0"
              controls-position="right"
              placeholder="请输入商品库存"
              class="full-width">
            </el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="市场价" prop="price">
            <el-input-number
              v-model="productForm.price"
              :min="0"
              :precision="2"
              controls-position="right"
              placeholder="请输入市场价"
              class="full-width">
            </el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="button-container">
      <el-button type="default" size="medium" @click="goBackStep('ruleForm')"
        >返回</el-button
      >
      <el-button
        type="primary"
        size="medium"
        @click="goNextStep('ruleForm')"
        class="next-button">
        <i class="el-icon-arrow-right"></i>
        下一步，填写商品促销
      </el-button>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'

export default {
  name: 'AddProduct',
  data() {
    var validateCategory = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('商品分类不能为空'));
      } else {
        callback();
      }
    };

    var validateName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('商品名称不能为空'));
      } else if (typeof value !== 'string') {
        callback(new Error('商品名称必须是字符串'));
      } else {
        callback();
      }
    };

    var validateCode = (rule, value, callback) => {
        const reg = /^\d+$/;
        if(!reg.test(value)){
          callback(new Error('必须是数字且不为空'))
        }
        callback();
    };

    var validateRemark = (rule, value, callback) => {
      if (value === null || value===undefined || value==='') {
        callback(new Error('商品简介不能为空'));
      } else if (typeof value !== 'string') {
        callback(new Error('商品简介必须是字符串'));
      } else {
        callback();
      }
    };

    var validateInventory = (rule, value, callback) => {
      if (value <= 0 || typeof value !== 'number' || isNaN(value)) {
        callback(new Error('商品库存必须是大于0的数字'));
      } else {
        callback();
      }
    };
    var validatePrice = (rule, value, callback) => {
      if (value <= 0 || typeof value !== 'number' || isNaN(value)) {
        callback(new Error('商品市场价必须是大于0的数字'));
      } else {
        callback();
      }
    };

    var validateSale = (rule, value, callback) => {
      if (value <= 0 || typeof value !== 'number' || isNaN(value)) {
        callback(new Error('商品销量必须是大于0的数字'));
      } else {
        callback();
      }
    };
    return {
      productForm: {
        category: '',//商品分类
        name: '',//商品名称
        code: '',//商品货号
        remark: '',//商品简介
        inventory: '',//库存
        price: '',//市场价
        sale: ''//销量
      },
      loading: false,
      categoryOptions: [],
      rules: {
        category:[
          {validator: validateCategory,trigger: 'blur'}
        ],
        name: [
          { validator: validateName, trigger: 'blur' }
        ],
        code: [
           { validator: validateCode, trigger: 'blur' }
        ],
        remark: [
          { validator: validateRemark, trigger: 'blur' }
        ],
        inventory: [
          { validator: validateInventory, trigger: 'blur' }
        ],
        price: [
          { validator: validatePrice, trigger: 'blur' }
        ],
        sale: [
          { validator: validateSale, trigger: 'blur' }
        ]
      },
    }
  },
      computed: {
        ...mapState('productForm', ['basicInfo']),
        promotionForm: {
          get() {
            return this.promotion
          },
          set(value) {
            this.UPDATE_PROMOTION(value)
          }
        }
      },
      //在created钩子中初始化数据
      created() {
        if (this.basicInfo) {
          this.productForm = this.basicInfo
        }
      },
      mounted() {
        const data = this.$store.getters['productForm/get_FIRST_tData']
        console.log(data)
        this.productForm = data
        this.fetchCategoryOptions();
      },
      methods: {
        goNextStep(formName){
            this.$refs[formName].validate((valid) => {
                  if(valid){
                    this.$store.dispatch('productForm/SET_first_DATA', this.productForm)
                    // 导航到下一步
                   this.$router.push('/home/addProduct/productPromotion');
                  }else{
                    console.log('error submit!!!');
                    return false;
                  }
            });
          },
        goBackStep(formName){
            this.$refs[formName].resetFields();
            this.$router.push('/home/GoodsCategory');
        },
        ...mapMutations('productForm', ['UPDATE_BASIC_INFO']),

        // 获取商品分类列表
        async fetchCategoryOptions() {
          this.loading = true;
          try {
            const response = await this.$axios.post('http://localhost:8080/Goods/selectGoodsTypeList');
            if (response.data.code === 20000) {
              this.categoryOptions = response.data.data.goodsTypeList.map(item => ({
                value: item.id,
                label: item.typeName,
                children: item.children.map(child => ({
                  value: child.id,
                  label: child.typeName
                }))
              }));
            } else {
              this.$message.error('获取商品分类失败：' + response.data.message);
            }
          } catch (error) {
            console.error('获取商品分类出错：', error);
            this.$message.error('获取商品分类失败，请检查网络连接');
          } finally {
            this.loading = false;
          }
        },
        //获取商品名称
        async fetchNameOptions() {
          this.loading = true;
          try {
            const response = await this.$axios.post('http://localhost:8080/Goods/selectGoodsTypeList');
            if (response.data.code === 20000) {
              this.nameOptions = response.data.data.goodsTypeList.map(item => ({
                value: item.id,
                label: item.typeName,
                children: item.children.map(child => ({
                  value: child.id,
                  label: child.typeName
                }))
              }));
            } else {
              this.$message.error('获取商品分类失败：' + response.data.message);
            }
          } catch (error) {
            console.error('获取商品分类出错：', error);
            this.$message.error('获取商品分类失败，请检查网络连接');
          } finally {
            this.loading = false;
          }
        },
        // 处理分类选择变化
        handleCategoryChange(value) {
          console.log('选中的分类ID:', value);
          this.UPDATE_BASIC_INFO({ ...this.productForm, category: value });
        },
        handlenameChange(value) {
          console.log('选中的商品名称ID:', value);
          this.UPDATE_BASIC_INFO({ ...this.productForm, name: value });
        },
      }
    }
</script>
<style scoped>
.add-product {
  padding: 30px;
  background: linear-gradient(to bottom, #ffffff, #f8f9fa);
  border-radius: 15px;
  height: calc(100vh - 120px);
  overflow-y: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

page-header {
  text-align: center;
  margin: 30px 0 40px;
}

page-header h2 {
  color: #2c3e50;
  font-size: 24px;
  margin-bottom: 10px;
}

.custom-steps {
  margin-bottom: 40px;
  padding: 20px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

:deep(.el-step__title.is-process) {
  color: #409EFF;
  font-weight: 600;
}

:deep(.el-step__head.is-process) {
  border-color: #409EFF;
  color: #409EFF;
}

.input-container {
  background: white;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

/* 表单项样式优化 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #2c3e50;
}

:deep(.el-input__inner) {
  border-radius: 8px;
  border: 1px solid #dcdfe6;
  padding: 0 15px;
  height: 42px;
  transition: all 0.3s ease;
}

:deep(.el-input__inner:hover) {
  border-color: #409EFF;
}

:deep(.el-textarea__inner) {
  border-radius: 8px;
  padding: 12px 15px;
  min-height: 120px;
  transition: all 0.3s ease;
}

.button-container {
  margin-top: 40px;
  text-align: center;
  padding: 20px;
}

.prev-button {
  margin-right: 15px;
}

.next-button {
  padding: 12px 25px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.next-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

/* 响应式优化 */
@media screen and (max-width: 768px) {
  .add-product {
    padding: 15px;
  }

  .input-container {
    padding: 20px;
  }

  .button-container {
    padding: 15px;
  }

  .prev-button,
  .next-button {
    width: 100%;
    margin: 10px 0;
  }
}
</style>



<!--handleSubmit(formName){-->
<!--this.$refs[formName].validate((valid) => {-->
<!--if(valid){-->
<!--this.$store.dispatch('productForm/SET_first_DATA', this.productForm)-->
<!--// 导航到下一步-->
<!--this.$router.push('/home/addProduct/productPromotion');-->
<!--}else{-->
<!--console.log('error submit!!!');-->
<!--return false;-->
<!--}-->
<!--});-->
<!--},-->
<!--dislogVisibleClose(formName){-->
<!--this.$refs[formName].resetFields();-->
<!--this.$router.push('/home/GoodsCategory');-->
<!--},-->













